# encoding=utf8

"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os
from resource_management import *
import ast
import socket

config = Script.get_config()

role_dict = config['configurations']['ambari-elastic-config']['elastic.node.role']
print(role_dict)

# 下载路径变量
es_download_url = config['configurations']['ambari-elastic-config']['elastic.package.download.url']

config = Script.get_config()
stack_root = Script.get_stack_root()  # 返回stack根目录
tmp_dir = Script.get_tmp_dir()
Logger.info(stack_root)

# 解决stack_root、tmp_dir

hostname = config['agentLevelParams']['hostname']  # 获取agent层面的参数,agent的hostname
ambari_server_host = config['ambariLevelParams']['ambari_server_host']  # 获取ambari层面的参数,ambari_server的host

elastic_user = config['configurations']['elastic-env']['elastic_user']  # 在elastic_env.xml中定义了elastic_user,返回elasticsearch
elastic_group = config['configurations']['elastic-env']['elastic_group']  # 在elastic_env.xml中定义了elastic_group,返回elasticsearch

version = default("/commandParams/version", "3.1.4.0-315")
Logger.info(version)

hdp_base_dir = os.path.join(stack_root, version)
elastic_base_dir = os.path.join(stack_root, version, 'elasticsearch')
# elastic_head_base_dir = os.path.join(stack_root, version, 'elasticsearch-head')
elastic_conf_base_dir = elastic_base_dir+'/config'
# elastic_head_site = elastic_head_base_dir + '/_site'

elastic_log_dir = config['configurations']['elastic-env']['elastic_log_dir'].rstrip("/")
elastic_pid_dir = config['configurations']['elastic-env']['elastic_pid_dir'].rstrip("/")
# elastic_head_pid_dir = config['configurations']['elastic-env']['elastic_head_pid_dir'].rstrip("/")
elastic_pid_file = format("{elastic_pid_dir}/elasticsearch.pid")
# elastic_head_pid_file = format("{elastic_head_pid_dir}/elasticsearch-head.pid")

service_packagedir = os.path.realpath(__file__).split('/scripts')[0]  # 返回params文件的绝对路径？
elastic_scripts_dir = os.path.join(service_packagedir, "scripts")

es_log_file = os.path.join(elastic_log_dir, 'elasticsearch-start.log')

# metrics_collector_host = default("/clusterHostInfo/metrics_collector_hosts", ['localhost'])[0]
# elasticsearch_service_host = default("/clusterHostInfo/elasticsearch_service_hosts", ['localhost'])[0]
elasticsearch_service_host = default("/clusterHostInfo/halo_master_hosts", ['localhost'])[0]
# elastic_download = os.path.join('http://', ambari_server_host, 'es/elasticsearch-6.4.0.tar.gz')
#elastic_download = config['configurations']['ambari-elastic-config']['elastic.package.download.url']
# elastic_head_download = os.path.join('http://', ambari_server_host, 'es/elasticsearch-head.tar.gz')
# nodejs_download = os.path.join('http://', ambari_server_host, 'es/node-v10.13.0-linux-x64.tar.gz')

cluster_name = config['configurations']['elastic-config']['cluster_name']
node_attr_rack = config['configurations']['elastic-config']['node_attr_rack']
path_data = config['configurations']['elastic-config']['data_path'].strip(",")

# 是否锁住内存,避免交换(swapped)带来的性能损失,默认值为false
elastic_bootstrap_memory_lock = str(config['configurations']['elastic-config']['bootstrap_memory_lock'])

# 是否支持过滤掉系统调用
bootstrap_system_call_filter = str(config['configurations']['elastic-config']['bootstrap_system_call_filter'])


network_host = config['configurations']['elastic-config']['network_host']
elasticsearch_port = config['configurations']['elastic-config']['elasticsearch_port']
http_cors_enabled = config['configurations']['elastic-config']['http_cors_enabled']

# discovery_zen_ping_unicast_hosts=config['clusterHostInfo']['all_hosts']
# 放开,不写死,这个的格式其实是组件名称+hosts
# elasticsearch_service_hosts = config['clusterHostInfo']['elasticsearch_service_hosts']
elasticsearch_service_hosts = config['clusterHostInfo']['halo_master_hosts']
# elasticsearch_service_hosts = ['173.18.12.2']

# Need to parse the comma separated hostnames to create the proper string format within the configuration file
# Elasticsearch expects the format ["host1","host2"]
discovery_zen_ping_unicast_hosts = '[' + ','.join('"' + x + '"' for x in elasticsearch_service_hosts) + ']'
discovery_zen_minimum_master_nodes = len(elasticsearch_service_hosts) / 2 + 1

gateway_recover_after_nodes = config['configurations']['elastic-config']['gateway_recover_after_nodes']
node_max_local_storage_nodes = config['configurations']['elastic-config']['node_max_local_storage_nodes']

action_destructive_requires_name = str(config['configurations']['elastic-config']['action_destructive_requires_name'])

# Elasticsearch expects boolean values to be true or false an will generate an error if you use True or False
# if action_destructive_requires_name == "True":
#     action_destructive_requires_name = "true"
# else:
#     action_destructive_requires_name = "false"

# head requires
# http_cors_enabled =config['configurations']['elastic-config']['http_cors_enabled']

http_cors_enabled = config['configurations']['elastic-config']['http_cors_enabled']


ping_timeout_default = config['configurations']['elastic-config']['ping_timeout_default']
discovery_zen_ping_timeout = config['configurations']['elastic-config']['discovery_zen_ping_timeout']
zookeeper_session_timeout = config['configurations']['elastic-config']['zookeeper.session.timeout']

# 设置不同节点的node.params

# if "ELASTIC_MASTER" in config['localComponents']:
#     node_master = 'true'
#     node_data = 'true'
#     node_ingest = 'true'
#     http_enabled = 'true'
# else:
#     node_master = 'hello master'
#     node_data = 'hello data'
#     node_ingest = 'hello ingest'
#     http_enabled = 'hello http'

role_dict = config['configurations']['ambari-elastic-config']['elastic.node.role']
role_dict = role_dict.strip()
elastic_role_dict = ast.literal_eval(role_dict)

# 获取当前主机ip
current_hostname = socket.gethostname()
current_ip = socket.gethostbyname(current_hostname)

node_master = elastic_role_dict[current_ip]['node_master']
node_data = elastic_role_dict[current_ip]['node_data']
node_ingest = elastic_role_dict[current_ip]['node_ingest']
http_enabled = elastic_role_dict[current_ip]['http_enabled']

elasticsearch_yml = config['configurations']['elastic-config']['content']

